<?php

App::import ( 'Vendor', 'weibo/weibooauth' );

class UsersController extends AppController {
	var $name = "Users";
	var $paginate = array ('Book' => array ('limit' => 10, 'joins' => array (array ('table' => 'books_series_link', 'alias' => 'bs', 'type' => 'left', 'conditions' => array ('bs.book=book.id' ) ) ), 'order' => array ('Book.id' => 'desc' ), 'contain' => array ('Author', 'Data', 'Comment', 'Series' ) ) );
	var $helpers = array ('Html', 'Text', 'Time',"Session" );
	//var $componets = array ( 'Session','Auth' );
	var $scaffold = 'admin';
	public $components = array('Session',
    'Auth'=> array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email','password'=>'password')
            )
        )
    )
);
	
	function login() {
		$this->set ( 'title_for_layout', '登录' );

	}
	
	function sina_callback() {
		
		$this->loadModel ( 'Weibo' );
		$this->set ( 'title_for_layout', '登录' );
		
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		
		if( isset($_REQUEST['code'])){
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			//try{
				$token = $o->getAccessToken('code',$keys);
			//}
			//catch(OAuthException $e){
				
			//}
		}
		
		if($token){
			$this->Session->write('token',$token);
			//$this->Cookie->write('weibojs_'.$o->client_id, http_build_query($token));
		}
		
		
		$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token['access_token'] );
		
		$uid_get = $c->get_uid();
		$uid = $uid_get['uid'];
		
		$this->Session->write('uid',$uid);
		
		
		$cur_weibo = $this->Weibo->findByRemote_id($uid);

		$user = null;
		if (!isset($cur_weibo) || empty ( $cur_weibo ) ) {
			$me = $c->show_user_by_id($uid);
			//如果当前用户未登录	
			$user ['User'] ['email'] = $me ['name'] . '@sina.weibo';
			$user ['User'] ['password'] = md5($token['access_token']);
			$user ['User'] ['name'] = $me ['screen_name'];
			$user ['User'] ['timestamp'] = date('Y-m-d H:i:s');
			$user ['User'] ['last_login'] = date('Y-m-d H:i:s');
			$user ['User'] ['point'] = 0;
			$user['User']['avatar_url'] = $me['profile_image_url'];
			$user['User']['gender'] = $me['gender'];
			$user['User']['description'] = $me['description'];
			$user['User']['remoteid'] = $uid;
				
				//创建一个用户
			$this->User->save ( $user );
			$user_id= $this->User->id;
				
			$weibo ['Weibo'] ['user'] = $user_id;
			$weibo ['Weibo'] ['provider'] = 'sina';
			$weibo ['Weibo'] ['token'] = '';
			$weibo ['Weibo'] ['token_secret'] = '';
			$weibo ['Weibo'] ['remote_id'] =$uid;
			
			$this->Weibo->save ( $weibo );
		}
		else{
			$me = $c->show_user_by_id($uid);
			$user = $cur_weibo['User'];
			$this->User->id = $user['id'];
			$this->User->saveField('last_login', date('Y-m-d H:i:s'));
			$this->User->saveField('avatar_url', $me['profile_image_url']);
			$this->User->saveField('gender', $me['gender'] );
			$this->User->saveField('description', $me['description'] );
			$this->User->saveField('remoteid',$me['id']);
		}

		
		if( $this->Auth->login($user) )
			$this->log("Login fail");
		else
			$this->log("login success");
		//$this->Cookie->write('user.email',$user['User']['email'],false,'+7 days');
		
		
		if( $this->Session->check('last_url') )
			$this->redirect ( $this->Session->read('last_url'));
		else {
			$this->redirect( "/");
		}
	}
	
	function register() {
		
		if ($this->data) {
			
			if (count ( $this->User->findByEmail ( $this->data ['User'] ['email'] ) ) > 0) {
				$this->flash ( '该Email地址已经被注册' );
			} elseif ($this->data ['User'] ['password'] != $this->data ['User'] ['password_confirm']) {
				$this->flash ( '两次密码输入不一致' );
			} else {
				
				$this->data ['User'] ['name'] = $this->data ['User'] ['email'];
				$this->data ['User'] ['last_login'] = date ( 'T' );
				$this->data ['User'] ['password'] = $this->Auth->password ( $this->data ['User'] ['password_confirm'] );
				$this->User->create ();
				$this->User->save ( $this->data );
				$this->redirect ( "users/login" );
			}
		}
	}
	
	function sina_login() {
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$aurl = $o->getAuthorizeURL( WB_CALLBACK_URL );
		
				
	
		if( isset($_REQUEST['last_url']))
			$last_url = $_REQUEST['last_url'];
		if( isset($last_url) )
		{
			$this->Session->write('last_url',$last_url);
		}
		else
		{
			$this->Session->write('last_url', $this->referer('/'));
		}
		

		$this->redirect ( $aurl );
	}
	
	function logout() {
		$this->Auth->logout ();
		$this->Session->destroy();
		$this->redirect ("/" );
	}
	
	function beforeFilter() {
		$this->Auth->allow('login','logout','sina_login','register','sina_callback');
		$this->Auth->authenticate = array ('username' => 'email', 'password' => 'password' );
		$this->Auth->loginErro = '登录信息错误';
	
	}
	
	function admin_login(){
	}

}


//$cur_weibo = $this->Weibo->find ( 'first', array ('condition' => array ('provider' => 'sina', 'remote_id' => $me ['id'] ) ) );
//		
//		
//		//如果已经登录
//		if ($this->Auth->user ()) {
//			//如果没有微博, 就创建一个
//			if (! $cur_weibo) {
//				$weibo ['Weibo'] ['user'] = $this->Auth->id;
//				$weibo ['Weibo'] ['provider'] = 'sina';
//				$weibo ['Weibo'] ['token'] = $last_key ['oauth_token'];
//				$weibo ['Weibo'] ['token_secret'] = $last_key ['oauth_token_secret'];
//				$weibo ['Weibo'] ['remote_id'] = $last_key ['user_id'];
//				
//				$this->Weibo->save ( $weibo );
//			}
//			else{
//				//已经有微博了
//				$this->$cur_weibo['User']['email']
//				
//			}
//		}
//		else{
//			//用户还没有登录
//		}
//		
//		//如果当前微博用户是第一次绑定
//		if (empty ( $cur_weibo )) {
//			
//			$cur_user = $this->Auth->user ();
//			$user_id = 0;
//			//如果当前用户未登录	
//			if (! isset ( $cur_user )) {
//				$user ['User'] ['email'] = $me ['name'] . '@sina.weibo';
//				$user ['User'] ['password'] = 'default';
//				$user ['User'] ['name'] = $me ['screen_name'];
//				$user ['User'] ['timestamp'] = time ();
//				$user ['User'] ['last_login'] = time ();
//				$user ['User'] ['point'] = 0;
//				
//				//创建一个用户
//				$this->User->save ( $user );
//				
//				//登录
//				$this->Auth->autoRedirect = false;
//				$this->Auth->login ( array ('User' => array ('email' => $user ['User'] ['email'], 'password' => 'default' ) ) );
//			} else {
//				$this->Session->write($this->Auth->sessionKey, $)
//			}
//			
//			$weibo ['Weibo'] ['user'] = $user_id;
//			$weibo ['Weibo'] ['provider'] = 'sina';
//			$weibo ['Weibo'] ['token'] = $last_key ['oauth_token'];
//			$weibo ['Weibo'] ['token_secret'] = $last_key ['oauth_token_secret'];
//			$weibo ['Weibo'] ['remote_id'] = $last_key ['user_id'];
//			
//			$this->Weibo->save ( $weibo );
//		
//		}